/*
 * Copyright (C) GSX Techedu Inc. All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 */

package com.nime.novel.crawl.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author bjhl
 * @description
 * @team wuhan operational dev.
 * @date 2020/7/1 下午1:35
 **/
public class GsonUtil {

    private static final Gson GSON = new Gson();

    public static <T> String toJson(T o) {
        if (null == o) {
            return null;
        }
        return GSON.toJson(o);
    }

    public static <T> T fromJson(String str, Class<T> clazz) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return GSON.fromJson(str, clazz);
    }

    /**
     * @param json list的序列化字符串
     * @param <T>  T类型
     * @return List<T>
     */
    public static <T> List<T> fromJsonArray(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return GSON.fromJson(json, TypeToken.getParameterized(List.class, clazz).getType());
    }
}
